package com.ymt.reliable.message.confirm.task;

import com.ymt.reliable.message.domain.TransactionMessage;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class Task implements Delayed {
    private String taskId;
    private Long submitTime;
    private Long delayTime;
    private TransactionMessage message;

    public Task(TransactionMessage message, Long delayTime) {
        this.taskId = message.getMessageId();
        this.message = message;
        this.delayTime = delayTime;
        this.submitTime = message.getCreateTime().getTime() + delayTime;
    }

    public String getTaskId() {
        return taskId;
    }

    public TransactionMessage getMessage() {
        return message;
    }

    public Long getSubmitTime() {
        return submitTime;
    }

    public Long getDelayTime() {
        return delayTime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return this.submitTime - System.currentTimeMillis();
    }

    @Override
    public int compareTo(Delayed o) {
        Task message = (Task) o;
        if (this.submitTime > message.getSubmitTime()) {
            return 1;
        } else if (this.submitTime < message.getSubmitTime()) {
            return -1;
        } else {
            return this.taskId.compareTo(message.getTaskId());
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Task task = (Task) o;

        return taskId.equals(task.taskId);
    }

    @Override
    public int hashCode() {
        return taskId.hashCode();
    }
}
